import gcoord from "../../miniprogram_npm/gcoord/dist/gcoord";
Page({
  data: {
    // 当前的位置
    latitude: "",
    longitude: "",
    // 画圆
    circles: [],
    nearByList: [], // 企业后台接口信息集合
    originList: [], // 原始列表数据
    markers: [], // 企业标记点集合
    markerId: "",
    qiyeTypeList: [
      {
        name: "电子信息",
        url1: " https://zx-1311146360.cos.ap-shanghai.myqcloud.com/version01/dzxx_1.png",
        url2: " https://zx-1311146360.cos.ap-shanghai.myqcloud.com/version01/dzxx_2.png",
      },
      {
        name: "数字经济",
        url1: " https://zx-1311146360.cos.ap-shanghai.myqcloud.com/version01/szjj_1.png",
        url2: " https://zx-1311146360.cos.ap-shanghai.myqcloud.com/version01/szjj_2.png",
      },
      {
        name: "高端装备制造",
        url1: " https://zx-1311146360.cos.ap-shanghai.myqcloud.com/version01/gszbzz_1.png",
        url2: " https://zx-1311146360.cos.ap-shanghai.myqcloud.com/version01/gszbzz_2.png",
      },
      {
        name: "生物医药",
        url1: " https://zx-1311146360.cos.ap-shanghai.myqcloud.com/version01/swyy_1.png",
        url2: " https://zx-1311146360.cos.ap-shanghai.myqcloud.com/version01/swyy_2.png",
      },
      {
        name: "集成电路",
        url1: " https://zx-1311146360.cos.ap-shanghai.myqcloud.com/version01/jcdl_1.png",
        url2: " https://zx-1311146360.cos.ap-shanghai.myqcloud.com/version01/jcdl_2.png",
      },
      {
        name: "汽车零部件",
        url1: " https://zx-1311146360.cos.ap-shanghai.myqcloud.com/version01/qclbj_1.png",
        url2: " https://zx-1311146360.cos.ap-shanghai.myqcloud.com/version01/qclbj_2.png",
      },
      {
        name: "先进材料",
        url1: " https://zx-1311146360.cos.ap-shanghai.myqcloud.com/version01/xjcl_1.png",
        url2: " https://zx-1311146360.cos.ap-shanghai.myqcloud.com/version01/xjcl_2.png",
      },
      {
        name: "软件服务",
        url1: " https://zx-1311146360.cos.ap-shanghai.myqcloud.com/version01/rjfw_1.png",
        url2: " https://zx-1311146360.cos.ap-shanghai.myqcloud.com/version01/rjfw_2.png",
      },
      {
        name: "航空航天",
        url1: " https://zx-1311146360.cos.ap-shanghai.myqcloud.com/version01/hkht_1.png",
        url2: " https://zx-1311146360.cos.ap-shanghai.myqcloud.com/version01/hkht_2.png",
      },
      // {
      //   name: "电子信息",
      //   url1: " https://zx-1311146360.cos.ap-shanghai.myqcloud.com/version01/dzxx_map_1.png",
      //   url2: " https://zx-1311146360.cos.ap-shanghai.myqcloud.com/version01/dzxx_map_2.png",
      // },
      // {
      //   name: "数字经济",
      //   url1: " https://zx-1311146360.cos.ap-shanghai.myqcloud.com/version01/szjj_map_1.png",
      //   url2: " https://zx-1311146360.cos.ap-shanghai.myqcloud.com/version01/szjj_map_2.png",
      // },
      // {
      //   name: "高端装备制造",
      //   url1: " https://zx-1311146360.cos.ap-shanghai.myqcloud.com/version01/gdzbzz_map_1.png",
      //   url2: " https://zx-1311146360.cos.ap-shanghai.myqcloud.com/version01/gdzbzz_map_2.png",
      // },
      // {
      //   name: "生物医药",
      //   url1: " https://zx-1311146360.cos.ap-shanghai.myqcloud.com/version01/swyw_map_1.png",
      //   url2: " https://zx-1311146360.cos.ap-shanghai.myqcloud.com/version01/swyw_map_2.png",
      // },
      // {
      //   name: "集成电路",
      //   url1: " https://zx-1311146360.cos.ap-shanghai.myqcloud.com/version01/jcdl_map_1.png",
      //   url2: " https://zx-1311146360.cos.ap-shanghai.myqcloud.com/version01/jcdl_map_2.png",
      // },
      // {
      //   name: "汽车零部件",
      //   url1: " https://zx-1311146360.cos.ap-shanghai.myqcloud.com/version01/qclbj_map_1.png",
      //   url2: " https://zx-1311146360.cos.ap-shanghai.myqcloud.com/version01/qclbj_map_2.png",
      // },
      // {
      //   name: "先进材料",
      //   url1: " https://zx-1311146360.cos.ap-shanghai.myqcloud.com/version01/xjcl_map_1.png",
      //   url2: " https://zx-1311146360.cos.ap-shanghai.myqcloud.com/version01/xjcl_map_2.png",
      // },
      // {
      //   name: "软件服务",
      //   url1: " https://zx-1311146360.cos.ap-shanghai.myqcloud.com/version01/rjfw_map_1.png",
      //   url2: " https://zx-1311146360.cos.ap-shanghai.myqcloud.com/version01/rjfw_map_2.png",
      // },
      // {
      //   name: "航空航天",
      //   url1: " https://zx-1311146360.cos.ap-shanghai.myqcloud.com/version01/hkht_map_1.png",
      //   url2: " https://zx-1311146360.cos.ap-shanghai.myqcloud.com/version01/hkht_map_2.png",
      // },
    ],
    allChanyeList: [
      "电子信息",
      "数字经济",
      "高端装备制造",
      "生物医药",
      "集成电路",
      "汽车零部件",
      "先进材料",
      "软件服务",
      "航空航天",
    ],
    tabLists: [
      "附近企业",
      "营收500万-1000万",
      "营收1000万以上",
      "有融资需求企业",
      "未结清信贷企业",
      "未结清小额贷款企业",
      "纳税A级企业",
    ],
    extraObj: {}, // 额外的查询条件
    activeIndex: 0, // 默认的产业选择
    actionType: 0, // 默认收缩
    pageNum: 1,
    total: "", // 附近企业总数
  },

  // 页面解析完成后执行
  onReady: function () {
    // 步骤一、常见地图实例对象
    this.mapCtx = wx.createMapContext("myMap");
    // this.locationBack();
  },
  onLoad: function (e) {
    this.initInfoByCenter(e);
    // 获取当前的位置信息
    // getApp().globalData.getLocation({
    //   type: "gcj02",
    //   success(res) {
    //     that.initInfoByCenter(e);
    //   },
    // });
    // this.initInfos();
  },

  /**
   * methods
   */
  // 获取页面节点信息的方法(nodeName 节点id名称)
  getNodeInfo (nodeName) {
    const query = this.createSelectorQuery();
    query.select(`#${nodeName}`).boundingClientRect();
    query.selectViewport().scrollOffset();
    query.exec((res) => {
      console.log(res, "res");
      this.setData({ scrollTop: res[0].height });
    });
  },
  initInfoByCenter (res) {
    //console.log(res)
    this.setData({
      longitude: this.transMarker([res.longitude, res.latitude])[0],
      latitude: this.transMarker([res.latitude, res.latitude])[1],
    });
    // center info
    this.setData({
      circles: [
        {
          latitude: res.latitude,
          longitude: res.longitude,
          color: "#7cb5ec88",
          opacity: 0.2,
          fillColor: "#7cb5ec88",
          radius: 1500,
          strokeWidth: 2,
        },
      ],
    });

    // 数据初始化
    this.initInfos();
  },
  // 初始化数据
  async initInfos () {
    // 获取周边企业的坐标
    await this.getNearByInfos();
    // 初始化markers
    this.initMarkers();
  },

  // 获取附近企业的坐标
  async getNearByInfos () {
    const params = {
      distance: "1.0",
      userLng: this.data.longitude,
      userLat: this.data.latitude,
      pageBO: {
        pageSize: 25,
        pageNum: this.data.pageNum,
      },
      keyIndustries: this.data.allChanyeList[this.data.activeIndex] + "产业",
    };

    console.log({ ...params, ...this.data.extraObj }, "附近企业查询条件");
    wx.showLoading({
      title: "加载中",
    });
    const { list, total } = await getApp().globalData.request(
      "/map/lookAround",
      { ...params, ...this.data.extraObj },
      "POST"
    );
    wx.hideLoading();
    console.log(list);
    // 原始列表数据
    this.setData({
      originList: this.data.originList.concat(list),
      total: total,
    });
    // 处理数据
    const resInfos = this.findSameList(this.data.originList);
    this.setData({
      nearByList: resInfos,
    });
    console.log(this.data.originList, "原始附近企业查询结果");
    console.log(this.data.nearByList, "附近企业查询结果");
  },

  // 初始化点标记
  initMarkers () {
    const markers = [];
    this.data.nearByList.forEach((val, index) => {
      const zuobiao = this.transMarker1([val[0].longitude, val[0].latitude]);
      // console.log(Math.floor((Math.random() * index)) * 0.0000001)
      val[0].longitude = zuobiao[0];
      val[0].latitude = zuobiao[1];
      markers.push({
        id: index,
        latitude: val[0].latitude,
        longitude: val[0].longitude,
        name: val[0].d2CorpName,
        corpKey: val[0].corpKey,
        iconPath:
          "https://zx-1311146360.cos.ap-shanghai.myqcloud.com/version01/zhoubian1.png",
        desc: "我现在的位置",
        title: val[0].d2CorpName,
        width: 14,
        height: 21,
        callout: {
          content: `${val[0].d2CorpName}${val.length > 0 ? "等" + val.length + "家企业" : ""
            },点击查看`,
          color: "#ffffff",
          bgColor: "#505d58", //需要6位的色值有效
          fontSize: 14,
          borderRadius: 2,
          padding: 5,
          display: "BYCLICK", //'BYCLICK':点击显示; 'ALWAYS':常显
        },
      });
    });
    // 中心点自定义样式
    // markers.push({
    //   id: 9999,
    //   latitude: this.data.circles[0].latitude,
    //   longitude: this.data.circles[0].longitude,
    //   name: "",
    //   iconPath:
    //     " https://zx-1311146360.cos.ap-shanghai.myqcloud.com/version01/center-location2.png",
    //   desc: "我现在的位置",
    //   title: "",
    //   width: 23,
    //   height: 31,
    // });
    this.setData({
      markers: markers,
    });
    // console.log(markers, "markers");
  },

  // 坐标系转化
  transMarker (item) {
    const resae = gcoord.transform(
      [item[0], item[1]],
      gcoord.GCJ02, // 当前坐标系
      gcoord.BD09 // 目标坐标系
    );
    return resae;
  },

  // 中心点坐标转化
  transMarker1 (item) {
    const resae = gcoord.transform(
      [item[0], item[1]],
      gcoord.BD09, // 当前坐标系
      gcoord.GCJ02 // 目标坐标系
    );
    return resae;
  },

  toprodetail (e) {
    wx.navigateTo({
      url: `/pages/mapDetail/mapDetail?corpKey=${e.detail.corpKey}&latitude=${e.detail.latitude}&longitude=${e.detail.longitude}&distance=${e.detail.distance}`,
    });
  },

  // 查找重复的数据,并且重新排列
  findSameList (item) {
    const needList = JSON.parse(JSON.stringify(item));
    // console.log(needList, 'needList')
    // 先去重复
    const singleList = this.removeDuplicateObj(needList);
    // console.log(singleList, 'singleList')
    const showList = [];
    singleList.forEach((val, index) => {
      const itemList = [];
      needList.forEach((pre) => {
        if (val.latitude === pre.latitude) {
          itemList.push(pre);
        }
      });
      showList.push(itemList);
    });
    // console.log(showList, "showList");
    return showList;
  },

  removeDuplicateObj (arr) {
    let obj = {};
    arr = arr.reduce((newArr, next) => {
      obj[next.latitude] ? "" : (obj[next.latitude] = 1 && newArr.push(next));
      return newArr;
    }, []);
    return arr;
  },

  // 跳转企业详情或者企业列表
  markerCalloutTap (e) {
    console.log(e.markerId, "e");
    if (this.data.nearByList[e.markerId].length > 1) {
      // 跳转到列表页面
      wx.navigateTo({
        url: `../../packageB/pages/businesses/businesses?businesses=${JSON.stringify(
          this.data.nearByList[e.markerId]
        )}`,
      });
    } else {
      // 跳转到详情页面
      wx.navigateTo({
        url: `/pages/mapDetail/mapDetail?corpKey=${this.data.nearByList[e.markerId][0].corpKey
          }&latitude=${this.data.nearByList[e.markerId][0].latitude}&longitude=${this.data.nearByList[e.markerId][0].longitude
          }&distance=${this.data.nearByList[e.markerId][0].distance}`,
      });
    }
  },

  // 扩展
  open () {
    this.setData({
      actionType: 1,
    });
    this.getNodeInfo("sticky1");
  },

  // 收缩
  close () {
    this.setData({
      actionType: 0,
    });
  },

  tabTuijian (e) {
    // console.log(e, "e");
    this.setData({
      extraObj: {},
    });
    switch (e.detail.index) {
      case 0:
        this.originInfo();
        break;
      case 1:
        const params1 = {
          businessIncomeLowerLimit: "500",
          businessIncomeUpperLimit: "1000",
        };
        this.setData({
          extraObj: params1,
        });
        this.originInfo();
        break;
      case 2:
        const params2 = {
          businessIncomeLowerLimit: "1000",
          businessIncomeUpperLimit: "50000",
        };
        this.setData({
          extraObj: params2,
        });
        this.originInfo();
        break;
      case 3:
        const params3 = {
          isLoan: "1",
        };
        this.setData({
          extraObj: params3,
        });
        this.originInfo();
        break;
      case 4:
        const params4 = {
          qutstandingLoans: "1",
        };
        this.setData({
          extraObj: params4,
        });
        this.originInfo();
        break;
      case 5:
        const params5 = {
          qutstandingSmallLoans: "1",
        };
        this.setData({
          extraObj: params5,
        });
        this.originInfo();
        break;
      case 6:
        const params6 = {
          taxALeavel: "1",
        };
        this.setData({
          extraObj: params6,
        });
        this.originInfo();
        break;
      default:
        break;
    }
  },

  // 滑动底部加载更多
  scrollBottom () {
    // this.onBottom();
    this.setData({
      pageNum: ++this.data.pageNum,
    });
    this.initInfos();
  },
  phone (event) {
    console.log(event.currentTarget.id);
    if (event.currentTarget.id) {
      wx.makePhoneCall({
        phoneNumber: event.currentTarget.id,
      });
    } else {
      Toast("暂无电话");
    }
  },
  location (e) {
    const longitude = this.transMarker1([
      e.currentTarget.dataset.one.longitude,
      e.currentTarget.dataset.one.latitude,
    ])[0];
    const latitude = this.transMarker1([
      e.currentTarget.dataset.one.longitude,
      e.currentTarget.dataset.one.latitude,
    ])[1];
    wx.openLocation({
      latitude: latitude,
      longitude: longitude,
      name: e.currentTarget.dataset.one.d2CorpName,
      address: e.currentTarget.dataset.one.d2Dom,
      scale: 18,
    });
  },

  // 产业切换
  clickCy (e) {
    // console.log(e, "e");
    if (e.currentTarget.dataset.index === this.data.activeIndex) return;
    this.setData({
      activeIndex: e.currentTarget.dataset.index,
    });
    // 切换后重置分页参数和列表原始数组
    this.setData({
      pageNum: 1,
      originList: [],
    });
    this.initInfos();
  },

  // 返回到当前定位视窗
  locationBack () {
    this.mapCtx.moveToLocation();
  },
  // 初始化
  originInfo () {
    this.setData({
      pageNum: 1,
      originList: [],
    });
    this.initInfos();
  },
});
